package com.cloud.pole.shop.service.order.impl;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cloud.pole.api.user.BaseUserApi;
import com.cloud.pole.common.constant.CommonConstants;
import com.cloud.pole.common.exception.BaseException;
import com.cloud.pole.common.msg.ApiRestResponse;
import com.cloud.pole.common.util.DateUtils;
import com.cloud.pole.common.util.jwt.IJWTInfo;
import com.cloud.pole.common.util.jwt.JWTInfo;
import com.cloud.pole.common.util.jwt.JwtTokenUtil;
import com.cloud.pole.common.util.security.MD5Utils;
import com.cloud.pole.feign.IUserAccountService;
import com.cloud.pole.feign.IUserService;
import com.cloud.pole.feign.IWeiXinService;
import com.cloud.pole.mapper.order.ShopOrderMapper;
import com.cloud.pole.shop.biz.goods.ShopGoodsBiz;
import com.cloud.pole.shop.biz.goods.ShopGoodsSpecBiz;
import com.cloud.pole.shop.biz.order.ShopOrderBiz;
import com.cloud.pole.shop.biz.order.ShopOrderDeliveryBiz;
import com.cloud.pole.shop.biz.order.ShopOrderItemsBiz;
import com.cloud.pole.shop.biz.order.ShopOrderPayBiz;
import com.cloud.pole.shop.biz.order.ShopOrderRefundBiz;
import com.cloud.pole.shop.biz.order.ShopOrderShoppingCartBiz;
import com.cloud.pole.shop.biz.shops.ShopShopsBiz;
import com.cloud.pole.shop.biz.user.ShopUserDeliAddrBiz;
import com.cloud.pole.shop.config.BusiConfiguration;
import com.cloud.pole.shop.constant.ShopCommonConstant;
import com.cloud.pole.shop.model.entity.goods.ShopGoods;
import com.cloud.pole.shop.model.entity.goods.ShopGoodsSpec;
import com.cloud.pole.shop.model.entity.order.ShopOrder;
import com.cloud.pole.shop.model.entity.order.ShopOrderAdd;
import com.cloud.pole.shop.model.entity.order.ShopOrderAdmin;
import com.cloud.pole.shop.model.entity.order.ShopOrderDelivery;
import com.cloud.pole.shop.model.entity.order.ShopOrderItems;
import com.cloud.pole.shop.model.entity.order.ShopOrderPay;
import com.cloud.pole.shop.model.entity.order.ShopOrderShoppingCart;
import com.cloud.pole.shop.model.entity.shops.ShopShops;
import com.cloud.pole.shop.model.entity.shops.ShopShopsWithBLOBs;
import com.cloud.pole.shop.model.entity.user.ShopUserDeliAddr;
import com.cloud.pole.shop.model.vo.UserCenterDataVo;
import com.cloud.pole.shop.model.vo.order.ShopOrderPageVo;
import com.cloud.pole.shop.model.vo.order.ShopOrderToConfirmByShopVo;
import com.cloud.pole.shop.model.vo.order.ShopOrderToConfirmVo;
import com.cloud.pole.shop.model.vo.order.ShopOrderVo;
import com.cloud.pole.shop.model.vo.order.ShopRecommendOrderPageVo;
import com.cloud.pole.shop.model.vo.order.ShopRecommendOrderVo;
import com.cloud.pole.shop.model.vo.order.ShopUserOrderDetailVo;
import com.cloud.pole.shop.model.vo.order.ShopUserOrderPageVo;
import com.cloud.pole.shop.model.vo.order.ShopUserOrderVo;
import com.cloud.pole.shop.rabbit.RabbitSender;
import com.cloud.pole.shop.service.goods.GoodsService;
import com.cloud.pole.shop.service.order.OrderService;
import com.cloud.pole.shop.service.shops.ShopShopsService;
import com.cloud.pole.shop.service.user.UserDeliAddrService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import lombok.extern.slf4j.Slf4j;

/*
*2019年1月30日
*cloud-user
*author:frank-chen
*/
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
	@Autowired
	private ShopOrderShoppingCartBiz shopOrderShoppingCartBiz;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private ShopShopsService shopShopsService;
	@Autowired
	private ShopGoodsBiz shopGoodsBiz;
	@Autowired
	private ShopGoodsSpecBiz shopGoodsSpecBiz;
	@Autowired
	private ShopShopsBiz shopShopsBiz;
	@Autowired
	private ShopOrderBiz shopOrderBiz;
	@Autowired
	private ShopOrderItemsBiz shopOrderItemsBiz;
	@Autowired
	private UserDeliAddrService userDeliAddrService;
	@Autowired
	private ShopUserDeliAddrBiz shopUserDeliAddrBiz;
	@Autowired
	private ShopOrderDeliveryBiz shopOrderDeliveryBiz;
	@Autowired
	private ShopOrderPayBiz shopOrderPayBiz;
	@Autowired
	private IUserAccountService userAccountService;
	@Autowired
	private ShopOrderRefundBiz shopOrderRefundBiz;
	@Autowired
	private ShopOrderMapper shopOrderMapper;
	@Autowired
	private IUserService userService;
	@Autowired
	private BusiConfiguration busiConfiguration;
	@Autowired
	private IWeiXinService weiXinService;
	@Autowired
	private RabbitSender rabbitSender;
	
	private static final int SEQ_MAX_VALUE = 999999; // 序列的最大值
	private static final int SEQ_MIN_VALUE = 100000; // 序列的最小值
	private static Integer msgSEQ; // 消息的报文体序列号

	/**
	 * 获取序列
	 * 
	 * @return
	 */
	public static String getMsgSeq() {
		int nMsgSeq = 0;
		String msg = "";
		if (msgSEQ == null) {
			msgSEQ = new Integer(SEQ_MIN_VALUE);
		}
		synchronized (msgSEQ) {
			nMsgSeq = msgSEQ.intValue();
			if (nMsgSeq > SEQ_MAX_VALUE)
				nMsgSeq = SEQ_MIN_VALUE;
			msgSEQ = new Integer(nMsgSeq + 1);
			nMsgSeq = msgSEQ.intValue();
		}
		msg = Integer.toString(nMsgSeq);
		return msg;
	}

	/**
	 * @param cartIds
	 *            多个cartId使用“,”隔开
	 * @param cartParams
	 *            店铺id-goodsId-goodsSpecId-数量,多个使用“,”隔开
	 */
	@Override
	public String addOrder(String token, String cartIds, String cartParams, String marketCode) throws Exception {
		// TODO Auto-generated method stub
		IJWTInfo jwtInfo = JwtTokenUtil.getInfoFromToken(token);
		String[] paramsArray = cartParams.split(",");
		if (paramsArray.length <= 0) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "cartParams错误");
		}
		String[] cartIdArray = cartIds.split(",");
		if (cartIdArray.length <= 0) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "cartIds错误");
		}
		// 订单列表
		List<ShopOrderAdd> shopOrderList = new ArrayList<ShopOrderAdd>();
		// 商家列表
		TreeSet<String> shopList = new TreeSet<String>();
		String orderIds = "";
		for (String paramItem : paramsArray) {
			String[] paramItemArray = paramItem.split("-");
			if (paramItemArray.length != 4) {
				throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "cartParams错误");
			}
			String shopId = paramItemArray[0];
			String goodsId = paramItemArray[1];
			String goodsSpecId = paramItemArray[2];
			String productNum = paramItemArray[3];
			/**
			 * 检测店铺、产品、规格有效状态、产品库存
			 */
			ShopShopsWithBLOBs shopShops = shopShopsBiz.selectById(Integer.parseInt(shopId));
			shopShopsService.checkShopsValid(shopShops);

			ShopGoods shopGoods = shopGoodsBiz.selectByPrimaryKey(Integer.parseInt(goodsId));
			goodsService.checkShoppingGoods(shopGoods);

			ShopGoodsSpec shopGoodsSpec = shopGoodsSpecBiz.selectById(Integer.parseInt(goodsSpecId));
			goodsService.checkGoodsSpec(shopGoodsSpec);
			// 检测库存是否足够
			if (shopGoods.getStockStatus() == -1) {
				throw new BaseException(CommonConstants.STATUS_ERROR_CODE, shopGoods.getTitle() + "库存不够");
			}
			if (shopGoodsSpec.getStockQuantity().intValue() < Integer.parseInt(productNum)) {
				throw new BaseException(CommonConstants.STATUS_ERROR_CODE, shopGoods.getTitle() + "库存不够");
			}
			shopList.add(shopId);
			ShopOrderAdd shopOrderAdd = new ShopOrderAdd();
			shopOrderAdd.setShopId(Integer.parseInt(shopId));
			shopOrderAdd.setGoodsId(Integer.parseInt(goodsId));
			shopOrderAdd.setGoodsSpecId(Integer.parseInt(goodsSpecId));
			shopOrderAdd.setProductNum(Integer.parseInt(productNum));
			shopOrderList.add(shopOrderAdd);
		}
		String orderSn = DateUtils.formatDate(new Date(), "yyyyMMddHHmmss") + getMsgSeq();
		String[] newShopList = new String[shopList.size()];
		for (int i = 0; i < newShopList.length; i++) {
			newShopList[i] = shopList.pollFirst();
			int shopId = Integer.parseInt(newShopList[i]);
			// 总价格
			int pricetol = 0;
			// 总运费
			int yunfeitol = 0;
			// 该订单、该商店商品的总毛重
			int tolwietght = 0;
			for (int j = 0; j < shopOrderList.size(); j++) {
				// 单价、总价（一个店铺/一个订单）
				if (shopId == shopOrderList.get(j).getShopId().intValue()) {
					int count = Integer.parseInt(shopOrderList.get(j).getProductNum().toString());
					long[] ret = priceofid(shopOrderList.get(j).getGoodsSpecId().toString(), count);
					long price = ret[0];
					long weight = ret[1];
					pricetol += (price * count);
					shopOrderList.get(j).setGoodsPrice(price);
					// shopOrderList.get(j).setAllprice(price * count);
					// 获取该商品的毛重
					tolwietght += count * weight;// 商品数量*每个商品毛重
				}
			}
			ShopShopsWithBLOBs shopShops = shopShopsBiz.selectById(shopId);
			int postFreeAmount = shopShops.getPostFreeAmount();
			String shopLogisticsArea = shopShops.getLogisticsArea();
			yunfeitol = calcFreight(postFreeAmount, shopLogisticsArea, pricetol, tolwietght);

			ShopOrder order = new ShopOrder();
			order.setShopId(shopId); // 店铺id
			order.setShopName(shopShops.getShopName());
			order.setUserId(Long.parseLong(jwtInfo.getId())); // 买家uid
			order.setUserName(jwtInfo.getUniqueName());
			order.setCreateTime(new Date());
			orderIds += "|" + orderSn + "|";
			order.setFreightAmount(Integer.parseInt(String.valueOf(yunfeitol)));
			order.setProductAmount(Integer.parseInt(String.valueOf(pricetol)));
			order.setOrderStatus(ShopOrder.ORDER_STATUS_DEFAULT);
			order.setOrderType(1);
			order.setOrderChannel("pc");
			order.setPayStatus(0);
			order.setLogisticsStatus(0);
			// order.setLogisticsType(1);
			order.setOrderSn(orderSn);
			order.setMerchantId(shopShops.getMerchantId());
			if(StringUtils.isNotBlank(marketCode)){
				order.setMarketCode(marketCode);
			}
			shopOrderBiz.insertSelective(order);

			for (int j = 0; j < shopOrderList.size(); j++) {
				ShopOrderAdd shopOrderAdd = shopOrderList.get(j);
				if (shopId == shopOrderAdd.getShopId().intValue()) {
					ShopOrderItems orderItem = new ShopOrderItems();
					// 查出购物车中选择的商品的价格和重量
					ShopGoodsSpec shopGoodsSpec = shopGoodsSpecBiz.selectById(shopOrderAdd.getGoodsSpecId());
					orderItem.setUnitPrice(shopOrderAdd.getGoodsPrice());
					orderItem.setUnitWeight(Long.valueOf(Integer.toString(shopGoodsSpec.getWeight())));
					orderItem.setGoodsSpecName(shopGoodsSpec.getName());
					orderItem.setGoodsSpecDescription(shopGoodsSpec.getDescription());
					orderItem.setMerchantPrice(shopGoodsSpec.getMenchantPrice().longValue());

					ShopGoods shopGoods = shopGoodsBiz.selectByPrimaryKey(shopOrderAdd.getGoodsId());
					orderItem.setTitle(shopGoods.getTitle());
					orderItem.setTitleImage(shopGoods.getTitleImage());
					orderItem.setOrderSn(orderSn);
					orderItem.setGoodsId(shopOrderAdd.getGoodsId());
					orderItem.setGoodsSpecId(shopOrderAdd.getGoodsSpecId());
					orderItem.setGoodsNature(2);
					orderItem.setServiceStartTime(new Date());
					orderItem.setProductNum(shopOrderAdd.getProductNum());
					orderItem.setTotalWeight(orderItem.getUnitWeight() * orderItem.getProductNum());
					orderItem.setTotalPrice(orderItem.getUnitPrice() * orderItem.getProductNum());
					orderItem.setActivityStatus(10);
					orderItem.setShopId(shopShops.getShopId());
					orderItem.setShopName(shopShops.getShopName());
					orderItem.setGoodsName(shopGoods.getName());
					orderItem.setSimpleTitle(shopGoods.getSimpleTitle());
					orderItem.setOnlyPayMethod(shopGoods.getOnlyPayMethod());
					orderItem.setMerchantId(shopShops.getMerchantId());
					shopOrderItemsBiz.insertSelective(orderItem);
				}
			}
		}
		// 删除购物车
		for (String cartId : cartIdArray) {
			ShopOrderShoppingCart msg = new ShopOrderShoppingCart();
			msg.setCartId(Integer.parseInt(cartId));
			msg.setUserId(Long.parseLong(jwtInfo.getId()));
			shopOrderShoppingCartBiz.delete(msg);
		}
		orderIds = URLEncoder.encode(orderIds, "UTF-8");
		//加入队列
		rabbitSender.sendOrder(orderSn);
		return orderIds;
	}

	/**
	 * 该商品的单价选择
	 * 
	 * @param specid
	 *            商品规则id
	 * @param count
	 *            商品数量
	 * @return
	 */
	public long[] priceofid(String specid, int count) {
		ShopGoodsSpec shopGoodsSpec = shopGoodsSpecBiz.selectById(Integer.parseInt(specid));
		long actPrice = 0, memberPrice = 0, price = 0, p = 0, p0 = 0, p1 = 0, p2 = 0, p3 = 0, weight = 0;

		weight = shopGoodsSpec.getWeight();
		if (count >= shopGoodsSpec.getLevel3Num() && shopGoodsSpec.getLevel3Num() > 0) {
			p3 = shopGoodsSpec.getLevel3Price();
		}
		if (count >= shopGoodsSpec.getLevel2Num() && shopGoodsSpec.getLevel2Num() > 0) {
			p2 = shopGoodsSpec.getLevel2Price();
		}
		if (count >= shopGoodsSpec.getLevel1Num() && shopGoodsSpec.getLevel1Num() > 0) {
			p1 = shopGoodsSpec.getLevel1Price();
		}
		p = shopGoodsSpec.getPrice(); // 原价
		memberPrice = shopGoodsSpec.getMemberPrice(); // 现价(会员价)
		actPrice = shopGoodsSpec.getActPrice(); // 活动价格

		long[] plist = { p, p0, p1, p2, p3, memberPrice, actPrice };
		for (int k = 0; k < plist.length; k++) {
			for (int h = k; h < plist.length; h++) {
				if (plist[k] > plist[h]) {
					long temp = plist[k];
					plist[k] = plist[h];
					plist[h] = temp;
				}
			}
		}
		for (int i = 0; i < plist.length; i++) {
			if (plist[i] > 0) {
				price = plist[i];
				break;
			}
		}
		long[] retLong = new long[2];
		retLong[0] = price;
		retLong[1] = weight;
		return retLong;
	}

	/**
	 * 计算重量
	 * 
	 * @param shopPostFreeAmount
	 * @param shopLogisticsArea
	 * @param shopTotalAmount
	 * @param shopTotalWeight
	 * @return
	 */
	public int calcFreight(long shopPostFreeAmount, String shopLogisticsArea, int shopTotalAmount,
			int shopTotalWeight) {
		int freightAmount = 0;
		if (shopTotalWeight == 0) {
			return freightAmount;
		}
		String logisticsArea[] = shopLogisticsArea.split(",");
		// 首重,首费,续重,续费
		int sz = Integer.parseInt(logisticsArea[0]);
		int sf = Integer.parseInt(logisticsArea[1]);
		int xz = Integer.parseInt(logisticsArea[2]);
		int xf = Integer.parseInt(logisticsArea[3]);
		if (shopTotalAmount >= shopPostFreeAmount) {
			return freightAmount;
		}
		if (shopTotalWeight <= sz) {
			freightAmount = sf;
			return freightAmount;
		}
		shopTotalWeight = shopTotalWeight - sz;
		freightAmount = sf + xf * (int) (Math.ceil(((double) shopTotalWeight) / ((double) xz)));
		return freightAmount;
	}

	/**
	 * 获取添加订单列表
	 * 
	 * @param token
	 * @param orderIds
	 * @return
	 */
	@Override
	public ShopOrderToConfirmVo getToConfirmOrderList(String token, String orderIds) throws Exception {
		// TODO Auto-generated method stub
		IJWTInfo jwtInfo = JwtTokenUtil.getInfoFromToken(token);
		ShopOrderToConfirmVo shopOrderToConfirmVo = new ShopOrderToConfirmVo();
		// 默认收货地址
		ShopUserDeliAddr shopUserDeliAddr = userDeliAddrService.getDefaultDeliAddr(token);
		shopOrderToConfirmVo.setDefaultDeliAddr(shopUserDeliAddr);
		// 根据订单查询
		orderIds = orderIds.substring(1, orderIds.length() - 1).trim();
		String[] orderArray = orderIds.split("\\|\\|");
		for (String orderId : orderArray) {
			// 查询订单信息
			ShopOrder shopOrder = shopOrderBiz.selectByPrimaryKey(orderId);
			if (shopOrder == null || shopOrder.getUserId().longValue() != Long.parseLong(jwtInfo.getId())) {
				throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "订单id错误");
			}

			// 查询店铺信息
			ShopShopsWithBLOBs shopShops = shopShopsBiz.selectById(shopOrder.getShopId());

			// 查询订单产品列表
			List<ShopOrderItems> shopOrderItemsList = shopOrderItemsBiz.selectOrderItemsList(orderId);
			if (shopOrderItemsList == null) {
				throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "订单明细错误");
			}
			// 验证订单规格
			for (ShopOrderItems shopOrderItems : shopOrderItemsList) {
				// 检测specId、goodId是否有效
				ShopGoods shopGoods = shopGoodsBiz.selectByPrimaryKey(shopOrderItems.getGoodsId());
				goodsService.checkShoppingGoods(shopGoods);
				ShopGoodsSpec shopGoodsSpec = shopGoodsSpecBiz.selectById(shopOrderItems.getGoodsSpecId());
				goodsService.checkGoodsSpec(shopGoodsSpec);

				// 检测库存是否足够
				if (shopGoods.getStockStatus() == -1) {
					throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "库存不够");
				}
				if (shopGoodsSpec.getStockQuantity().intValue() < shopOrderItems.getProductNum().intValue()) {
					throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "库存不够");
				}

			}
			ShopOrderToConfirmByShopVo shopOrderToConfirmByShopVo = new ShopOrderToConfirmByShopVo();
			shopOrderToConfirmByShopVo.setShopName(shopShops.getShopName());
			shopOrderToConfirmByShopVo.setShopOrder(shopOrder);
			shopOrderToConfirmByShopVo.setShopOrderItemsList(shopOrderItemsList);
			shopOrderToConfirmVo.getShopOrderList().add(shopOrderToConfirmByShopVo);
		}
		return shopOrderToConfirmVo;
	}

	/**
	 * 确认订单（保存收货地址，用户留言）
	 * 
	 * @param token
	 * @param orderIds
	 * @param userRemak
	 * @param addrId
	 * @return
	 */
	@Override
	public Long confirmOrders(String token, String orderIds, String userRemak, Integer addrId, Integer logisticsType,
			Integer payMethod, String recommandMarketCode) throws Exception {
		IJWTInfo jwtInfo = JwtTokenUtil.getInfoFromToken(token);
		
		ApiRestResponse<BaseUserApi> result = userService.getUserByMarketCode(recommandMarketCode);
		
		// 验证收货地址
		ShopUserDeliAddr shopUserDeliAddr = null;
		if (addrId != null) {
			shopUserDeliAddr = shopUserDeliAddrBiz.selectByPrimaryKey(addrId);
			if (shopUserDeliAddr == null
					|| shopUserDeliAddr.getUserId().longValue() != Long.parseLong(jwtInfo.getId())) {
				throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "addrId错误");
			}
		}
		// 总金额
		long totalPrice = 0;
		// 总重量
		long totalFreight = 0;
		// 总优惠
		long totalPromotion = 0;
		String shopIdStr = "";
		String platformIdStr = "";
		// 根据订单查询
		String orderSnS = orderIds;
		orderIds = orderIds.substring(1, orderIds.length() - 1).trim();
		String[] orderArray = orderIds.split("\\|\\|");
		Long payId = 0L;
		for (String orderId : orderArray) {
			// 查询订单信息
			ShopOrder shopOrder = shopOrderBiz.selectByPrimaryKey(orderId);
			if (shopOrder == null || shopOrder.getUserId().longValue() != Long.parseLong(jwtInfo.getId())) {
				throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "订单id错误");
			}
			if (shopOrder.getOrderStatus().intValue() != ShopOrder.ORDER_STATUS_DEFAULT
					&& shopOrder.getOrderStatus().intValue() != ShopOrder.ORDER_STATUS_COMFIRM) {
				throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "订单状态错误");
			}
			totalPrice += shopOrder.getProductAmount();
			totalFreight += shopOrder.getFreightAmount();
			shopIdStr += "|" + shopOrder.getShopId() + "|";
			platformIdStr += "|" + shopOrder.getPlatformId() + "|";

			if (shopUserDeliAddr != null) {
				shopOrder.setDeliAddr(shopUserDeliAddr.getProvinceName() + shopUserDeliAddr.getCityName()
						+ shopUserDeliAddr.getDistrictName() + shopUserDeliAddr.getAddress());
				shopOrder.setDeliName(shopUserDeliAddr.getDeliName());
				shopOrder.setDeliTel(shopUserDeliAddr.getTel());
			}

			shopOrder.setCustRemark(userRemak);
			shopOrder.setLogisticsType(logisticsType);
			shopOrder.setPayMethod(payMethod);
			shopOrder.setOrderStatus(ShopOrder.ORDER_STATUS_COMFIRM);
			
			if(result.getData() != null){
				shopOrder.setRecommendUserId(result.getData().getUserId());
				shopOrder.setMarketCode(recommandMarketCode);
			}
			
			shopOrderBiz.updateSelectiveById(shopOrder);

			ShopOrderDelivery shopOrderDelivery = new ShopOrderDelivery();
			shopOrderDelivery.setDeliAddress(shopOrder.getDeliAddr());
			shopOrderDelivery.setUserId(Long.parseLong(jwtInfo.getId()));
			shopOrderDelivery.setUserName(jwtInfo.getUniqueName());
			if (shopUserDeliAddr != null) {
				shopOrderDelivery.setDeliName(shopUserDeliAddr.getDeliName());
				shopOrderDelivery.setDeliTel(shopUserDeliAddr.getTel());
			}
			shopOrderDelivery.setOrderSn(orderId);
			shopOrderDelivery.setFreight(shopOrder.getFreightAmount());

			shopOrderDelivery.setShopId(shopOrder.getShopId());
			shopOrderDelivery.setMerchantId(shopOrder.getMerchantId());

			// 查询是否已经插入订单配送信息
			ShopOrderDelivery searchOrderDelivery = shopOrderDeliveryBiz.selectByOrderSn(orderId);
			if (searchOrderDelivery == null) {

				shopOrderDeliveryBiz.insert(shopOrderDelivery);
			} else {
				shopOrderDeliveryBiz.updateSelectiveById(shopOrderDelivery);
			}
			String strPgOrderS = MD5Utils.md5Hex(orderSnS);
			/**
			 * 存在未支付的，重新发起支付的，需要先删除支付记录，再插入记录
			 */
			shopOrderPayBiz.deleteByOrderSn(orderSnS);
			ShopOrderPay pay = new ShopOrderPay();
			pay.setOrderSnS(orderSnS); // 订单串
			pay.setPgOrderSn(strPgOrderS); // 发给第三方支付的订单号
			pay.setPgPayAmount(totalPrice + totalFreight);// 支付金额
			pay.setPgPayStatus(-1); // 支付状态，初始为支付－1
			pay.setCreateTime(new Date());
			pay.setPgType(""); // 支付类型
			pay.setRemark(""); // 支付备注
			pay.setUserId(Long.parseLong(jwtInfo.getId()));// 买家uid
			pay.setUserName(jwtInfo.getUniqueName());
			pay.setShopIdS(shopIdStr);// 店铺ID
			pay.setPlatforms(platformIdStr);// 平台ID
			shopOrderPayBiz.insertUseGeneratedKeys(pay);
			payId = pay.getPayId();
		}
		return payId;
	}

	/**
	 * 立即购买（加入订单、保存收货地址、用户留言）
	 */
	@Override
	public String immediatePurchase(String token, Integer specId, Integer productNum) throws Exception {
		IJWTInfo jwtInfo = JwtTokenUtil.getInfoFromToken(token);
		// 订单列表
		List<ShopOrderAdd> shopOrderList = new ArrayList<ShopOrderAdd>();
		// 商家列表
		String orderIds = "";

		/**
		 * 检测店铺、产品、规格有效状态、产品库存
		 */
		ShopGoodsSpec shopGoodsSpec = shopGoodsSpecBiz.selectById(specId);
		goodsService.checkGoodsSpec(shopGoodsSpec);

		ShopGoods shopGoods = shopGoodsBiz.selectByPrimaryKey(shopGoodsSpec.getGoodsId());
		goodsService.checkShoppingGoods(shopGoods);

		ShopShopsWithBLOBs shopShops = shopShopsBiz.selectById(shopGoods.getShopId());
		shopShopsService.checkShopsValid(shopShops);

		// 检测库存是否足够
		if (shopGoods.getStockStatus() == -1) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, shopGoods.getTitle() + "库存不够");
		}
		if (shopGoodsSpec.getStockQuantity().intValue() < productNum.intValue()) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, shopGoods.getTitle() + "库存不够");
		}
		// 总价格
		int pricetol = 0;
		// 总运费
		int yunfeitol = 0;
		// 该订单、该商店商品的总毛重
		int tolwietght = 0;
		long[] ret = priceofid(String.valueOf(specId), productNum);
		long price = ret[0];
		long weight = ret[1];
		pricetol += (price * productNum);
		// 获取该商品的毛重
		tolwietght = (int) (productNum.intValue() * weight);// 商品数量*每个商品毛重

		int postFreeAmount = shopShops.getPostFreeAmount();
		String shopLogisticsArea = shopShops.getLogisticsArea();
		yunfeitol = calcFreight(postFreeAmount, shopLogisticsArea, pricetol, tolwietght);

		ShopOrder payOrder = new ShopOrder();
		// payOrder.setAllprice(Long.parseLong(String.valueOf(pricetol)));
		payOrder.setShopId(shopShops.getShopId()); // 店铺id
		payOrder.setUserId(Long.parseLong(jwtInfo.getId())); // 买家uid
		payOrder.setUserName(jwtInfo.getUniqueName());
		payOrder.setCreateTime(new Date());
		String orderSn = DateUtils.formatDate(new Date(), "yyyyMMddHHmmss") + getMsgSeq();
		orderIds += "|" + orderSn + "|";
		payOrder.setFreightAmount(Integer.parseInt(String.valueOf(yunfeitol)));
		payOrder.setProductAmount(Integer.parseInt(String.valueOf(pricetol)));
		payOrder.setOrderStatus(1);
		payOrder.setOrderType(1);
		payOrder.setOrderChannel("pc");
		payOrder.setPayStatus(0);
		payOrder.setLogisticsStatus(0);
		payOrder.setLogisticsType(1);
		payOrder.setOrderSn(orderSn);
		payOrder.setShopName(shopShops.getShopName());
		shopOrderBiz.insertSelective(payOrder);

		ShopOrderItems orderItem = new ShopOrderItems();
		// 查出购物车中选择的商品的价格和重量
		orderItem.setUnitPrice((long) price);
		log.info("unitPrice[" + orderItem.getUnitPrice() + "]");
		orderItem.setUnitWeight(Long.valueOf(Integer.toString(shopGoodsSpec.getWeight())));
		orderItem.setGoodsSpecName(shopGoodsSpec.getName());
		orderItem.setGoodsSpecDescription(shopGoodsSpec.getDescription());
		orderItem.setMerchantPrice(shopGoodsSpec.getMenchantPrice().longValue());

		orderItem.setTitle(shopGoods.getTitle());
		orderItem.setTitleImage(shopGoods.getTitleImage());
		orderItem.setOrderSn(orderSn);
		orderItem.setGoodsId(shopGoods.getGoodsId());
		orderItem.setGoodsSpecId(shopGoodsSpec.getSpceId());
		orderItem.setGoodsNature(2);
		orderItem.setServiceStartTime(new Date());
		orderItem.setProductNum(productNum);
		orderItem.setTotalWeight(orderItem.getUnitWeight() * orderItem.getProductNum());
		orderItem.setTotalPrice(orderItem.getUnitPrice() * orderItem.getProductNum());

		log.info("setTotalPrice[" + orderItem.getTotalPrice() + "]");

		orderItem.setActivityStatus(10);
		orderItem.setShopId(shopShops.getShopId());
		orderItem.setShopName(shopShops.getShopName());
		orderItem.setGoodsName(shopGoods.getName());
		orderItem.setSimpleTitle(shopGoods.getSimpleTitle());
		orderItem.setOnlyPayMethod(shopGoods.getOnlyPayMethod());
		shopOrderItemsBiz.insertSelective(orderItem);
		//加入队列
		rabbitSender.sendOrder(orderSn);
		return orderIds;
	}

	@Override
	public ShopUserOrderPageVo getPageUserOrderList(String token, Integer searchType, Integer pageSize, Integer pageNum)
			throws Exception {
		// TODO Auto-generated method stub
		// 查询订单列表
		IJWTInfo jwtInfo = JwtTokenUtil.getInfoFromToken(token);
		Long userId = Long.parseLong(jwtInfo.getId());
		ShopUserOrderPageVo shopUserOrderVo = new ShopUserOrderPageVo();
		PageHelper.startPage(pageNum, pageSize);
		List<ShopOrder> orderList = shopOrderBiz.selectOrderListByUserId(userId, searchType);
		PageInfo<ShopOrder> pageInfo = new PageInfo<ShopOrder>(orderList);
		List<ShopUserOrderVo> orderDetailVoList = new ArrayList<ShopUserOrderVo>();
		if (orderList != null) {
			for (ShopOrder shopOrder : orderList) {
				ShopOrderVo shopOrderVo = new ShopOrderVo();
				BeanUtils.copyProperties(shopOrder, shopOrderVo);
				shopOrderVo.setOrderStatusStr(getOrderStatusStr(shopOrderVo.getOrderStatus()));
				shopOrderVo.setLogisticsStatusStr(getLogisticsStatusStr(shopOrderVo.getLogisticsStatus()));
				shopOrderVo.setPayStatusStr(getPayStatusStr(shopOrderVo.getPayStatus()));
				shopOrderVo.setPayMethodStr(this.getPayMethodStr(shopOrderVo.getPayMethod()));
				shopOrderVo.setLogisticsTypeStr(this.getLogisticsTypeStr(shopOrderVo.getLogisticsType()));

				ShopUserOrderVo userOrderVo = new ShopUserOrderVo();
				// 查询订单产品
				List<ShopOrderItems> shopOrderItemsList = shopOrderItemsBiz
						.selectOrderItemsList(shopOrder.getOrderSn());
				userOrderVo.setShopOrder(shopOrderVo);
				userOrderVo.setShopOrderItemsList(shopOrderItemsList);
				orderDetailVoList.add(userOrderVo);
			}
		}
		shopUserOrderVo.setRows(orderDetailVoList);
		shopUserOrderVo.setLimit(Long.valueOf(pageInfo.getPageSize()));
		shopUserOrderVo.setPage(Long.valueOf(pageInfo.getPageNum()));
		shopUserOrderVo.setTotal(Long.valueOf(pageInfo.getPages()));
		// 统计数据
		shopUserOrderVo.setNeedCommentCount(
				Long.valueOf(shopOrderBiz.selectCountOrderByUserId(userId, ShopOrder.SEARCH_TYPE_NEED_COMMENT)));
		shopUserOrderVo.setNeedPayCount(
				Long.valueOf(shopOrderBiz.selectCountOrderByUserId(userId, ShopOrder.SEARCH_TYPE_NEED_PAY)));
		shopUserOrderVo.setNeedReceiveCount(
				Long.valueOf(shopOrderBiz.selectCountOrderByUserId(userId, ShopOrder.SEARCH_TYPE_NEED_RECEIVE)));
		shopUserOrderVo.setNeedSendCount(
				Long.valueOf(shopOrderBiz.selectCountOrderByUserId(userId, ShopOrder.SEARCH_TYPE_NEED_SEND)));
		return shopUserOrderVo;
	}

	@Override
	public ShopUserOrderDetailVo getUserOrderDetail(String token, String orderId) throws Exception {
		// TODO Auto-generated method stub
		// 查询订单列表
		IJWTInfo jwtInfo = JwtTokenUtil.getInfoFromToken(token);
		Long userId = Long.parseLong(jwtInfo.getId());
		ShopOrder shopOrder = shopOrderBiz.selectByPrimaryKey(orderId);
		ShopOrderVo shopOrderVo = new ShopOrderVo();
		BeanUtils.copyProperties(shopOrder, shopOrderVo);

		shopOrderVo.setOrderStatusStr(getOrderStatusStr(shopOrderVo.getOrderStatus()));
		shopOrderVo.setLogisticsStatusStr(getLogisticsStatusStr(shopOrderVo.getLogisticsStatus()));
		shopOrderVo.setPayStatusStr(getPayStatusStr(shopOrderVo.getPayStatus()));
		shopOrderVo.setPayMethodStr(this.getPayMethodStr(shopOrderVo.getPayMethod()));
		shopOrderVo.setLogisticsTypeStr(this.getLogisticsTypeStr(shopOrderVo.getLogisticsType()));
		ShopUserOrderDetailVo shopUserOrderDetailVo = new ShopUserOrderDetailVo();
		if (shopOrder == null) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "orderId错误");
		}
		if (shopOrder.getUserId().longValue() != userId.longValue()) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "orderId错误");
		}
		List<ShopOrderItems> shopOrderItemsList = shopOrderItemsBiz.selectOrderItemsList(shopOrder.getOrderSn());
		if (shopOrderItemsList == null) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "orderId错误");
		}
		for (ShopOrderItems shopOrderItems : shopOrderItemsList) {

		}
		// 付款方式
		if (shopOrder.getPayType() != null) {
			ApiRestResponse<String> apiResponse = userAccountService.getAccountTypeName(shopOrder.getPayType());
			if (apiResponse.getStatus() == CommonConstants.STATUS_OK_CODE) {
				shopOrderVo.setPayTypeName(apiResponse.getData());
			}
		}
		shopUserOrderDetailVo.setShopOrderVo(shopOrderVo);
		shopUserOrderDetailVo.setShopOrderItemsList(shopOrderItemsList);
		shopUserOrderDetailVo.setShopOrderDelivery(shopOrderDeliveryBiz.selectByOrderSn(shopOrder.getOrderSn()));
		return shopUserOrderDetailVo;
	}

	@Override
	public PageInfo<ShopOrderAdmin> selectPageShopOrderAdminVoList(String token, Map<String, Object> map,
			Integer pageNo, Integer pageSize) throws Exception {
		IJWTInfo jwtInfo = JwtTokenUtil.getInfoFromToken(token);
		int userType = jwtInfo.getType();
		Integer merchantId = null;
		// 商家管理
		if (userType == JWTInfo.USER_TYPE_MERCHANTT) {
			if (StringUtils.isEmpty(jwtInfo.getAttr1())) {
				throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "merchantId为空");
			}
			merchantId = Integer.parseInt(jwtInfo.getAttr1());
			map.put("merchantId", merchantId);
		}
		PageHelper.startPage(pageNo, pageSize);
		List<ShopOrderAdmin> list = shopOrderBiz.selectPageShopOrderAdminList(map);
		PageInfo<ShopOrderAdmin> page = new PageInfo<ShopOrderAdmin>(list);
		return page;
	}

	@Override
	public Boolean confirmReceiveGoods(String token, String orderId) throws Exception {
		IJWTInfo jwtInfo = JwtTokenUtil.getInfoFromToken(token);
		Long userId = Long.parseLong(jwtInfo.getId());
		ShopOrder shopOrder = shopOrderBiz.selectByPrimaryKey(orderId);
		if (shopOrder == null) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "orderId错误");
		}
		if (shopOrder.getUserId().longValue() != userId.longValue()) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "orderId错误");
		}
		if (shopOrder.getOrderStatus() != ShopOrder.ORDER_STATUS_DELIVERED
				|| shopOrder.getPayStatus() != ShopOrder.PAY_STATUS_YES
				|| (shopOrder.getLogisticsStatus() != ShopOrder.LOGISTICS_STATUS_SENT
						&& shopOrder.getLogisticsStatus() != ShopOrder.LOGISTICS_STATUS_WAITING_TAKE)) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "已发货或待收货的订单才能签收");
		}
		shopOrder = new ShopOrder();
		shopOrder.setOrderSn(orderId);
		shopOrder.setOrderStatus(ShopOrder.ORDER_STATUS_FINISH);
		shopOrder.setLogisticsStatus(ShopOrder.LOGISTICS_STATUS_SIGNED);
		shopOrder.setAcceptTime(new Date());
		shopOrderBiz.updateSelectiveById(shopOrder);

		ShopOrderDelivery delivery = shopOrderDeliveryBiz.selectByOrderSn(orderId);
		if (delivery != null) {
			delivery.setLogisticsReceiveTime(new Date());
			shopOrderDeliveryBiz.updateSelectiveById(delivery);
		}
		return true;
	}

	@Override
	public Boolean delOrder(String token, String orderId) throws Exception {
		IJWTInfo jwtInfo = JwtTokenUtil.getInfoFromToken(token);
		Long userId = Long.parseLong(jwtInfo.getId());
		ShopOrder shopOrder = shopOrderBiz.selectByPrimaryKey(orderId);
		if (shopOrder == null) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "orderId错误");
		}
		if (shopOrder.getUserId().longValue() != userId.longValue()) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "orderId错误");
		}
		shopOrder = new ShopOrder();
		shopOrder.setOrderSn(orderId);
		shopOrder.setDeleteFlag(1);
		shopOrderBiz.updateSelectiveById(shopOrder);
		return true;
	}

	/**
	 * 订单状态(-1:交易关闭（24小时未付款）,1:生成订单(待付款), 2:确认订单(待付款), 3:已付款(待发货), 4:已发货（待收货),
	 * 10:交易完成（用户点击已收货或发货7天自动收货）
	 */
	@Override
	public String getOrderStatusStr(int orderStatus) throws Exception {
		// TODO Auto-generated method stub
		String strInfo = "";
		switch (orderStatus) {
		case -2:
			strInfo = "取消订单";
			break;
		case -1:
			strInfo = "作废订单";
			break;
		case 1:
			strInfo = "待付款";
			break;
		case 2:
			strInfo = "待付款";
			break;
		case 3:
			strInfo = "已付款";
			break;
		case 4:
			strInfo = "已发货";
			break;
		case 10:
			strInfo = "交易完成";
			break;
		default:
			strInfo = "";
			break;
		}
		return strInfo;
	}

	/**
	 * 支付状态0：未支付，1：部分支付，2：已支付，3：已退款
	 */
	@Override
	public String getPayStatusStr(int payStatus) throws Exception {
		// TODO Auto-generated method stub
		String strInfo = "";
		switch (payStatus) {
		case 0:
			strInfo = "未支付";
			break;
		case 1:
			strInfo = "部分支付";
			break;
		case 2:
			strInfo = "已支付";
			break;
		case 3:
			strInfo = "已退款";
			break;
		default:
			strInfo = "";
			break;
		}
		return strInfo;
	}

	/**
	 * 配送状态0：未发送，1: 配货中，2:等待客户提货，3：已发送，4: 已经签收，5：客户拒收，6：物流异常
	 */
	@Override
	public String getLogisticsStatusStr(int logisticsStatus) throws Exception {
		// TODO Auto-generated method stub
		String strInfo = "";
		switch (logisticsStatus) {
		case 0:
			strInfo = "未发送";
			break;
		case 1:
			strInfo = "配货中";
			break;
		case 2:
			strInfo = "等待客户提货";
			break;
		case 3:
			strInfo = "已发送";
			break;
		case 4:
			strInfo = "已经签收";
			break;
		case 5:
			strInfo = "客户拒收";
			break;
		case 6:
			strInfo = "物流异常";
			break;
		default:
			strInfo = "";
			break;
		}
		return strInfo;
	}

	@Override
	public String getLogisticsTypeStr(int logisticsType) throws Exception {
		// TODO Auto-generated method stub
		String strInfo = "";
		switch (logisticsType) {
		case 1:
			strInfo = "第三方物流";
			break;
		case 2:
			strInfo = "上门自提";
			break;
		case 3:
			strInfo = "送货上门";
			break;
		default:
			strInfo = "";
			break;
		}
		return strInfo;
	}

	@Override
	public String getPayMethodStr(int payMethod) throws Exception {
		// TODO Auto-generated method stub
		String strInfo = "";
		switch (payMethod) {
		case 1:
			strInfo = "在线支付";
			break;
		case 2:
			strInfo = "到店支付";
			break;
		case 3:
			strInfo = "货到付款";
			break;
		case 10:
			strInfo = "分期付";
			break;
		default:
			strInfo = "";
			break;
		}
		return strInfo;
	}

	@Override
	public ShopOrderAdmin selectOrderAdminById(String token, String id) throws Exception {
		IJWTInfo jwtInfo = JwtTokenUtil.getInfoFromToken(token);
		// 验证权限
		int userType = jwtInfo.getType();
		Integer merchantId = null;
		ShopOrder shopOrder = shopOrderBiz.selectById(id);
		if (shopOrder == null) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "订单不存在");
		}
		if (userType == JWTInfo.USER_TYPE_MERCHANTT) {
			merchantId = Integer.parseInt(jwtInfo.getAttr1());
			if (shopOrder.getMerchantId() == null || shopOrder.getMerchantId().intValue() != merchantId) {
				throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "无权限查询");
			}
		}

		ShopOrderAdmin shopOrderAdmin = new ShopOrderAdmin();
		BeanUtils.copyProperties(shopOrder, shopOrderAdmin);
		List<ShopOrderItems> items = shopOrderItemsBiz.selectOrderItemsList(id);
		shopOrderAdmin.setItems(items);
		return shopOrderAdmin;
	}

	@Override
	public ShopOrderPageVo getPageShopOrderList(String token, Integer shopId, Integer searchType, Integer pageSize,
			Integer pageNum) throws Exception {
		// TODO Auto-generated method stub
		// 查询订单列表
		IJWTInfo jwtInfo = JwtTokenUtil.getInfoFromToken(token);
		Long userId = Long.parseLong(jwtInfo.getId());
		// 验证用户是否店铺人员

		List<ShopShops> shopList = shopShopsBiz.selectListByManageUserId(userId, shopId);
		if (shopList == null || shopList.size() == 0) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "数据无查询权限");
		}
		ShopOrderPageVo orderPage = new ShopOrderPageVo();
		PageHelper.startPage(pageNum, pageSize);
		List<ShopOrder> orderList = shopOrderBiz.selectOrderListByShopId(shopId, searchType);
		PageInfo<ShopOrder> pageInfo = new PageInfo<ShopOrder>(orderList);
		List<ShopUserOrderVo> orderDetailVoList = new ArrayList<ShopUserOrderVo>();
		if (orderList != null) {
			for (ShopOrder shopOrder : orderList) {
				ShopOrderVo shopOrderVo = new ShopOrderVo();
				BeanUtils.copyProperties(shopOrder, shopOrderVo);
				shopOrderVo.setOrderStatusStr(getOrderStatusStr(shopOrderVo.getOrderStatus()));
				shopOrderVo.setLogisticsStatusStr(getLogisticsStatusStr(shopOrderVo.getLogisticsStatus()));
				shopOrderVo.setPayStatusStr(getPayStatusStr(shopOrderVo.getPayStatus()));
				shopOrderVo.setPayMethodStr(this.getPayMethodStr(shopOrderVo.getPayMethod()));
				shopOrderVo.setLogisticsTypeStr(this.getLogisticsTypeStr(shopOrderVo.getLogisticsType()));
				ShopUserOrderVo userOrderVo = new ShopUserOrderVo();
				// 查询订单产品
				List<ShopOrderItems> shopOrderItemsList = shopOrderItemsBiz
						.selectOrderItemsList(shopOrder.getOrderSn());
				userOrderVo.setShopOrder(shopOrderVo);
				userOrderVo.setShopOrderItemsList(shopOrderItemsList);
				orderDetailVoList.add(userOrderVo);
			}
		}
		orderPage.setRows(orderDetailVoList);
		orderPage.setLimit(Long.valueOf(pageInfo.getPageSize()));
		orderPage.setPage(Long.valueOf(pageInfo.getPageNum()));
		orderPage.setTotal(Long.valueOf(pageInfo.getPages()));
		// 统计数据
		orderPage.setNeedDealCount(
				Long.valueOf(shopOrderBiz.selectCountOrderByShopId(shopId, ShopOrder.SEARCH_TYPE_SHOP_NEED_DEAL)));
		return orderPage;
	}

	@Override
	public Boolean confirmDeliverOffLine(String token, String orderId) throws Exception {
		// TODO Auto-generated method stub
		IJWTInfo jwtInfo = JwtTokenUtil.getInfoFromToken(token);
		Long userId = Long.parseLong(jwtInfo.getId());

		// 查询订单
		ShopOrder shopOrder = shopOrderBiz.selectByPrimaryKey(orderId);
		if (shopOrder == null) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "订单不存在");
		}
		// 查询用户是否有权限
		List<ShopShops> shopList = shopShopsBiz.selectListByManageUserId(userId, shopOrder.getShopId());
		if (shopList == null || shopList.size() == 0) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "订单无权限");
		}
		if (shopOrder.getPayMethod() == ShopOrder.ORDER_STATUS_FINISH) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "订单已完成，不用重复处理");
		}
		if (shopOrder.getPayMethod() == ShopOrder.PAY_METHOD_CASH_ON_DELIVERY
				|| shopOrder.getPayMethod() == ShopOrder.PAY_METHOD_TO_SHOP) {
			// 订单状态
			if (shopOrder.getOrderStatus() == ShopOrder.ORDER_STATUS_COMFIRM
					&& shopOrder.getPayStatus() == ShopOrder.PAY_STATUS_NO) {
				// 处理确认发货、确认付款
				shopOrder = new ShopOrder();
				shopOrder.setOrderSn(orderId);
				shopOrder.setOrderStatus(ShopOrder.ORDER_STATUS_DELIVERED);
				shopOrder.setLogisticsStatus(ShopOrder.LOGISTICS_STATUS_SENT);
				shopOrder.setPayType(ShopCommonConstant.SHOP_PAY_TYPE_OFFLINE);
				shopOrder.setPayTime(new Date());
				shopOrder.setPayStatus(ShopOrder.PAY_STATUS_YES);
				shopOrderBiz.updateSelectiveById(shopOrder);
			} else {
				throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "订单状态错误");
			}
		} else {
			if (shopOrder.getOrderStatus() == ShopOrder.ORDER_STATUS_PAY_OK
					&& shopOrder.getPayStatus() == ShopOrder.PAY_STATUS_YES) {
				// 处理确认发货
				shopOrder = new ShopOrder();
				shopOrder.setOrderSn(orderId);
				shopOrder.setOrderStatus(ShopOrder.ORDER_STATUS_DELIVERED);
				shopOrder.setLogisticsStatus(ShopOrder.LOGISTICS_STATUS_SENT);
				shopOrderBiz.updateSelectiveById(shopOrder);
			} else {
				throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "订单状态错误");
			}
		}
		return true;
	}

	@Override
	public int addShopOrderShippingAddress(ShopOrder shopOrder) {
		 return shopOrderBiz.addShopOrderShippingAddress(shopOrder);
	}

	@Override
	public UserCenterDataVo getUserCenterData(String token) throws Exception{
		IJWTInfo jwtInfo = JwtTokenUtil.getInfoFromToken(token);
		Long userId = Long.parseLong(jwtInfo.getId());
		UserCenterDataVo userCenterDataVo = new UserCenterDataVo();
		// 统计数据
		userCenterDataVo.setNeedCommentCount(
				Long.valueOf(shopOrderBiz.selectCountOrderByUserId(userId, ShopOrder.SEARCH_TYPE_NEED_COMMENT)));
		userCenterDataVo.setNeedPayCount(
				Long.valueOf(shopOrderBiz.selectCountOrderByUserId(userId, ShopOrder.SEARCH_TYPE_NEED_PAY)));
		userCenterDataVo.setNeedReceiveCount(
				Long.valueOf(shopOrderBiz.selectCountOrderByUserId(userId, ShopOrder.SEARCH_TYPE_NEED_RECEIVE)));
		userCenterDataVo.setNeedSendCount(
				Long.valueOf(shopOrderBiz.selectCountOrderByUserId(userId, ShopOrder.SEARCH_TYPE_NEED_SEND)));
		userCenterDataVo.setRefundCount(shopOrderRefundBiz.selectOrderRefundCountByUserId(userId));
		
		ApiRestResponse<BaseUserApi> apiResponse = userService.getBaseUser(token);
		if (apiResponse.getStatus() == CommonConstants.STATUS_OK_CODE) {
			userCenterDataVo.setMarketCode(apiResponse.getData().getMarketCode());
		}
		return userCenterDataVo;
	}
	
	@Override
	public ShopOrder selectById(String token, String orderSn) throws Exception{
		IJWTInfo jwtInfo = JwtTokenUtil.getInfoFromToken(token);
		Long userId = Long.parseLong(jwtInfo.getId());
		ShopOrder order = shopOrderBiz.selectById(orderSn);
		if(!order.getUserId().equals(userId)){
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "订单无权限");
		}
		return order;
	}

	@Override
	public Boolean cancelOrder(String token, String orderId) throws Exception {
		IJWTInfo jwtInfo = JwtTokenUtil.getInfoFromToken(token);
		Long userId = Long.parseLong(jwtInfo.getId());
		ShopOrder shopOrder = shopOrderBiz.selectByPrimaryKey(orderId);
		if (shopOrder == null) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "orderId错误");
		}
		if (shopOrder.getUserId().longValue() != userId.longValue()) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "orderId错误");
		}
		if(!shopOrder.getPayStatus().equals(0)){
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "订单支付状态错误");
		}
		shopOrder.setOrderStatus(-2);
		shopOrderBiz.updateSelectiveById(shopOrder);
		return true;
	}

	@Override
	public ShopRecommendOrderPageVo getRecommendOrderList(String token, Integer searchType, Integer pageSize, Integer pageNum) throws Exception {
		// 查询订单列表
		IJWTInfo jwtInfo = JwtTokenUtil.getInfoFromToken(token);
		Long userId = Long.parseLong(jwtInfo.getId());
		ShopRecommendOrderPageVo shopRecommendOrderPageVo = new ShopRecommendOrderPageVo();
		PageHelper.startPage(pageNum, pageSize);
		List<ShopRecommendOrderVo> orderList = shopOrderBiz.selectOrderListByRecommendId(userId, searchType);
		PageInfo<ShopRecommendOrderVo> pageInfo = new PageInfo<ShopRecommendOrderVo>(orderList);
		if (orderList != null) {
			for (ShopRecommendOrderVo shopOrder : orderList) {
				shopOrder.setOrderStatusStr(getOrderStatusStr(shopOrder.getOrderStatus()));
				// 查询订单产品
				List<ShopOrderItems> shopOrderItemsList = shopOrderItemsBiz
						.selectOrderItemsList(shopOrder.getOrderSn());
				shopOrder.setShopOrderItemsList(shopOrderItemsList);
			}
		}
		shopRecommendOrderPageVo.setRows(orderList);
		shopRecommendOrderPageVo.setLimit(Long.valueOf(pageInfo.getPageSize()));
		shopRecommendOrderPageVo.setPage(Long.valueOf(pageInfo.getPageNum()));
		shopRecommendOrderPageVo.setTotal(Long.valueOf(pageInfo.getPages()));
		return shopRecommendOrderPageVo;
	}
	
	@Override
	public String createRechargeOrder(String token, Integer specId, Integer productNum, String openId, String mobile) throws Exception {
		IJWTInfo jwtInfo = JwtTokenUtil.getInfoFromToken(token);
		/**
		 * 检测店铺、产品、规格有效状态、产品库存
		 */
		ShopGoodsSpec shopGoodsSpec = shopGoodsSpecBiz.selectById(specId);
		goodsService.checkGoodsSpec(shopGoodsSpec);

		ShopGoods shopGoods = shopGoodsBiz.selectByPrimaryKey(shopGoodsSpec.getGoodsId());
		goodsService.checkShoppingGoods(shopGoods);

		ShopShopsWithBLOBs shopShops = shopShopsBiz.selectById(shopGoods.getShopId());
		shopShopsService.checkShopsValid(shopShops);

		// 总价格
		int pricetol = 0;
		long[] ret = priceofid(String.valueOf(specId), productNum);
		long price = ret[0];
		pricetol += (price * productNum);

		ShopOrder payOrder = new ShopOrder();
		payOrder.setShopId(shopShops.getShopId()); // 店铺id
		payOrder.setUserId(Long.parseLong(jwtInfo.getId())); // 买家uid
		payOrder.setUserName(jwtInfo.getUniqueName());
		payOrder.setCreateTime(new Date());
		String orderSn = DateUtils.formatDate(new Date(), "yyyyMMddHHmmss") + getMsgSeq();
		payOrder.setFreightAmount(0);
		payOrder.setProductAmount(Integer.parseInt(String.valueOf(pricetol)));
		payOrder.setOrderType(10);
		payOrder.setOrderChannel("pc");
		payOrder.setPayStatus(0);
		payOrder.setLogisticsStatus(0);
		payOrder.setLogisticsType(1);
		payOrder.setOrderSn(orderSn);
		payOrder.setShopName(shopShops.getShopName());
		payOrder.setPayMethod(1);
		payOrder.setPayType(2);
		payOrder.setOrderStatus(ShopOrder.ORDER_STATUS_COMFIRM);
		payOrder.setAttr1(mobile);
		shopOrderBiz.insertSelective(payOrder);

		ShopOrderItems orderItem = new ShopOrderItems();
		// 查出购物车中选择的商品的价格和重量
		orderItem.setUnitPrice((long) price);
		log.info("unitPrice[" + orderItem.getUnitPrice() + "]");
		orderItem.setUnitWeight(Long.valueOf(Integer.toString(shopGoodsSpec.getWeight())));
		orderItem.setGoodsSpecName(shopGoodsSpec.getName());
		orderItem.setGoodsSpecDescription(shopGoodsSpec.getDescription());
		orderItem.setMerchantPrice(shopGoodsSpec.getMenchantPrice().longValue());

		orderItem.setTitle(shopGoods.getTitle());
		orderItem.setTitleImage(shopGoods.getTitleImage());
		orderItem.setOrderSn(orderSn);
		orderItem.setGoodsId(shopGoods.getGoodsId());
		orderItem.setGoodsSpecId(shopGoodsSpec.getSpceId());
		orderItem.setGoodsNature(2);
		orderItem.setServiceStartTime(new Date());
		orderItem.setProductNum(productNum);
		orderItem.setTotalWeight(orderItem.getUnitWeight() * orderItem.getProductNum());
		orderItem.setTotalPrice(orderItem.getUnitPrice() * orderItem.getProductNum());

		log.info("setTotalPrice[" + orderItem.getTotalPrice() + "]");

		orderItem.setActivityStatus(10);
		orderItem.setShopId(shopShops.getShopId());
		orderItem.setShopName(shopShops.getShopName());
		orderItem.setGoodsName(shopGoods.getName());
		orderItem.setSimpleTitle(shopGoods.getSimpleTitle());
		orderItem.setOnlyPayMethod(shopGoods.getOnlyPayMethod());
		shopOrderItemsBiz.insertSelective(orderItem);
		
		String shopIdStr = "|" + payOrder.getShopId() + "|";
		
		String orderSnS = "|" + orderSn + "|";
		String nonceStr = Long.toString(System.currentTimeMillis());
		String strPgOrderS = MD5Utils.md5Hex(orderSnS + nonceStr);

		ShopOrderPay pay = new ShopOrderPay();
		pay.setOrderSnS("|" + orderSn + "|"); // 订单串
		pay.setPgPayAmount(payOrder.getProductAmount().longValue());// 支付金额
		pay.setPgPayStatus(-1); // 支付状态，初始为支付－1
		pay.setCreateTime(new Date());
		pay.setPgType(""); // 支付类型
		pay.setRemark(""); // 支付备注
		pay.setUserId(Long.parseLong(jwtInfo.getId()));// 买家uid
		pay.setUserName(jwtInfo.getUniqueName());
		pay.setShopIdS(shopIdStr);// 店铺ID
		pay.setPgOrderSn(strPgOrderS); // 发给第三方支付的订单号
		shopOrderPayBiz.insertUseGeneratedKeys(pay);
		
		
		Integer payJoinId = busiConfiguration.getWeiXinPayJoinId();
		String callBackParams = Integer.toString(payJoinId);
		ApiRestResponse<String> response = weiXinService.unifiedOrderJsApi(payJoinId, strPgOrderS, pay.getPgPayAmount(), openId, callBackParams);
		if(response.getStatus() != CommonConstants.STATUS_OK_CODE) {
			throw new BaseException(response.getStatus(), response.getMessage());
		}	
		return response.getData();
	}


	/**
	 * 处理订单超时未付款
	 * @param orderSn
	 * @return
	 * @throws Exception
	 */
	@Override
	public Boolean synOrderDelay(String orderSn) throws Exception {
		//查询订单
		ShopOrder shopOrder = shopOrderBiz.selectByPrimaryKey(orderSn);
		if(shopOrder == null) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "订单不存在");
		}
		// 在线支付的订单，并且未付款
		if (shopOrder.getPayMethod() == ShopOrder.PAY_METHOD_ONLINE){
			if(((shopOrder.getOrderStatus() == ShopOrder.ORDER_STATUS_DEFAULT || shopOrder.getOrderStatus() == ShopOrder.ORDER_STATUS_COMFIRM)) &&
					shopOrder.getPayStatus() == ShopOrder.PAY_STATUS_NO) {
				//处理确认发货、确认付款
				shopOrder = new ShopOrder();
				shopOrder.setOrderSn(orderSn);
				shopOrder.setOrderStatus(ShopOrder.ORDER_STATUS_CLOSE);
				shopOrder.setCloseNote("订单超时未支付");
				shopOrder.setCloseTime(new Date());
				shopOrderBiz.updateSelectiveById(shopOrder);
			}
		}
		return Boolean.TRUE;
	}
}
